const fs = require("fs-extra");
const path = require("path");
const inquirer = require("inquirer");
const Creator = require("./Creator");
const getPromptModules = require("./utils/getPromptModules");
const logStep = require('../../util/logStep');
const logInfo = require('../../util/logInfo');

async function creatApp(name, options) {
  logStep("1. 解析项目名：'.' 的快捷处理、名字的合法性验证");
  const appPath = path.join(__dirname, "../test-apps/", name);

  logInfo(appPath);
  logStep("2. 判断是否已存在目录");
  if (fs.existsSync(appPath)) {
    const { action } = await inquirer.prompt([
      {
        name: "action",
        type: "list",
        message: "文件已存在，请选择操作",
        choices: [
          { name: "覆盖", value: "overwrite" },
          { name: "合并", value: "merge" },
          { name: "取消", value: false },
        ],
      },
    ]);
    if (!action) {
      process.exit(0);
    } else if (action === "overwrite") {
      await fs.remove(appPath);
    }
  }
  logStep("3. 开始创建项目 new Creator(name,appPath,getPromptModules())");
  const creater = new Creator(name, appPath, getPromptModules());
  await creater.create();
}

module.exports = function (...args) {
  return creatApp(...args).catch((err) => {
    console.log(err);
    console.log("报错，退出");
    process.exit(1);
  });
};
